package com.yaoweigroup.community.ui.home;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.OnlineAdapter;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Repair;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.LoginUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 在线物业
 * 
 * @author xi
 * 
 */
public class OnlineWyActivity extends Activity implements OnClickListener {

	private ListView listView;
	private OnlineAdapter adapter;
	private List<Repair> list;

	private RelativeLayout report_rl;
	private RelativeLayout record_rl;
	private TextView report_tv;
	private TextView record_tv;
	private ImageView record_iv;
	private ImageView report_iv;
	private ScrollView scrollView;
	private RelativeLayout left_rl;

	private EditText name_et;
	private EditText address_et;
	private EditText content_et;
	private EditText realname_et;

	private UserInfo userInfo;
	private SharePreferenceUtil util;
	private Dialog dialog;
	private Button ok_btn;
	private ObjectMapper mapper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_online_wy);
		mapper = new ObjectMapper();
		ok_btn = (Button) findViewById(R.id.ok_btn);
		ok_btn.setOnClickListener(this);
		util = new SharePreferenceUtil(this, Constant.prf);
		name_et = (EditText) findViewById(R.id.name_et);
		address_et = (EditText) findViewById(R.id.address_et);
		content_et = (EditText) findViewById(R.id.content_et);
		realname_et = (EditText) findViewById(R.id.realname_et);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		scrollView = (ScrollView) findViewById(R.id.scrollView);
		report_rl = (RelativeLayout) findViewById(R.id.report_rl);
		report_rl.setOnClickListener(this);
		record_rl = (RelativeLayout) findViewById(R.id.record_rl);
		record_rl.setOnClickListener(this);
		record_iv = (ImageView) findViewById(R.id.record_iv);
		report_iv = (ImageView) findViewById(R.id.report_iv);
		report_tv = (TextView) findViewById(R.id.report_tv);
		record_tv = (TextView) findViewById(R.id.record_tv);

		report_tv = (TextView) findViewById(R.id.report_tv);
		record_tv = (TextView) findViewById(R.id.record_tv);
		record_iv = (ImageView) findViewById(R.id.record_iv);
		report_iv = (ImageView) findViewById(R.id.report_iv);

		list = new ArrayList<Repair>();
		listView = (ListView) findViewById(R.id.listView);
		adapter = new OnlineAdapter(this, list);
		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				if (repairs != null && repairs.size() > 0) {
					Intent intent = new Intent(OnlineWyActivity.this,
							RecoderActivity.class);
					intent.putExtra("detail", repairs.get(arg2));
					startActivity(intent);
				}

			}
		});
		dialog = DialogUtil.createWaitDialog(this, "提交中，请稍等!..");
		userInfo = (UserInfo) util.loadObject("user");
		if (userInfo != null) {
			address_et.setText(userInfo.getAddress());
			name_et.setText(userInfo.getUsername());
			realname_et.setText(userInfo.getPhone());
			uId = userInfo.getUid();
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.report_rl:
			report_iv.setVisibility(View.VISIBLE);
			record_iv.setVisibility(View.GONE);
			record_tv.setTextColor(Color.parseColor("#5A5A5A"));
			report_tv.setTextColor(Color.parseColor("#F56A2A"));
			scrollView.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			break;
		case R.id.record_rl:
			obtainData();

			break;
		case R.id.left_rl:
			finish();
			break;
		case R.id.ok_btn:
			doSubmit();
			break;
		}
	}

	private String uId = "";
	private int type = 0;

	private void obtainData() {
		type = 1;
		userInfo = (UserInfo) util.loadObject("user");
		if (userInfo == null) {

			Toast.makeText(this, "请先登录", 500).show();
			return;
		}
		list.clear();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", userInfo.getUid());
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json;charset=UTF-8");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.queryRepair, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								String data = obj.getString("data");
								repairs = mapper.readValue(data,
										new TypeReference<List<Repair>>() {
										});
								handler.sendEmptyMessage(LIST_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								handler.sendEmptyMessage(LIST_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(LIST_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(LIST_FAIL);

					}

				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		isNew = false;

	}

	private void doSubmit() {

		if (userInfo == null) {
			Toast.makeText(this, "请登陆以后再提交!", 500).show();
			return;
		}

		String name = name_et.getText().toString();
		String phone = realname_et.getText().toString();
		String address = address_et.getText().toString();
		String content = content_et.getText().toString();

		if (name.length() == 0 || phone.length() == 0 || address.length() == 0
				|| content.length() == 0) {

			Toast.makeText(this, "请认真填写你提交的内容", 500).show();
			return;
		}
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", userInfo.getUid());
		jsonUtil.add("name", name);
		jsonUtil.add("phone", phone);
		jsonUtil.add("address", address);
		jsonUtil.add("content", content);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json;charset=UTF-8");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.addRepair, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								handler.sendEmptyMessage(SUBMIT_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = SUBMIT_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(SUBMIT_FAIL);

							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(SUBMIT_FAIL);

					}

				});
	}

	private boolean isNew = false;
	public final int SUBMIT_SUCCESS = 0x2210;
	public final int SUBMIT_FAIL = SUBMIT_SUCCESS + 1;
	public final int LIST_SUCCESS = SUBMIT_SUCCESS + 2;
	public final int LIST_FAIL = SUBMIT_SUCCESS + 3;
	public final int NEED_LOGIN = SUBMIT_SUCCESS + 4;
	private List<Repair> repairs;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case SUBMIT_SUCCESS:
				content_et.setText("");
				obtainData();
				isNew = true;
				break;
			case SUBMIT_FAIL:
				String errorMsg = "提交失败";
				if (msg.obj != null)
					errorMsg = msg.obj.toString();
				Toast.makeText(OnlineWyActivity.this, errorMsg, 500).show();
				break;
			case NEED_LOGIN:
				LoginUtil
						.isLoginSuccess(OnlineWyActivity.this, handler, mapper);
				break;
			case LoginUtil.LOGIN_SUCCESS:
				userInfo = (UserInfo) util.loadObject("user");
				if (type == 0) {
					doSubmit();
				} else {
					obtainData();
				}
				break;
			case LIST_SUCCESS:
				list.clear();
				if (repairs != null && repairs.size() > 0) {
					LogUtil.d("wxf", "repairs=" + repairs.size());
					list.addAll(repairs);
					adapter.setDataChange(list);
				} else {
					// Toast.makeText(OnlineWyActivity.this, "暂无报修记录",
					// 500).show();
				}
				report_iv.setVisibility(View.GONE);
				record_iv.setVisibility(View.VISIBLE);
				report_tv.setTextColor(Color.parseColor("#5A5A5A"));
				record_tv.setTextColor(Color.parseColor("#F56A2A"));
				listView.setVisibility(View.VISIBLE);
				scrollView.setVisibility(View.GONE);
				break;
			case LIST_FAIL:

				break;

			}
		};
	};
}
